package com.shanwen.shopping.adapter;

import android.content.Context;

import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonAdapter;
import com.classic.core.utils.DataUtil;
import com.classic.core.utils.MoneyUtil;
import com.shanwen.shopping.R;
import com.shanwen.shopping.consts.Consts;
import com.shanwen.shopping.dao.ShoppingCartItem;
import com.shanwen.shopping.imageload.ImageLoadByPicasso;
import com.shanwen.shopping.utils.EventUtil;
import com.shanwen.shopping.utils.Utils;
import com.shanwen.shopping.view.QuantityView;

import java.util.List;


/**
 * 商品支付页面列表适配器
 */
public class GoodsPayAdapter extends CommonAdapter<ShoppingCartItem> {
    private Context mContext;
    private List<ShoppingCartItem> data;
    public GoodsPayAdapter(Context context, int layoutResId, List<ShoppingCartItem> data) {
        super(context, layoutResId, data);
        this.mContext = context;
        this.data = data;
    }

    @Override
    public void onUpdate(BaseAdapterHelper helper, final ShoppingCartItem item, final int position) {
        QuantityView quantityView = helper.getView(R.id.goods_pay_item_quantity_view);
        quantityView.setTag(position);
        Utils.setQuantityClick(mContext, quantityView);
        quantityView.setOnQuantityChangeListener(new QuantityView.OnQuantityChangeListener() {
            @Override
            public void onQuantityChanged(int oldQuantity, int newQuantity, boolean programmatically) {
                data.get(position).setNumber(newQuantity);
                EventUtil.post(calculateTotalPrice(), Consts.EVENT_QUANTITY_CHANGE);
            }

            @Override
            public void onLimitReached() {

            }
        });

//        final int number = quantityView.getQuantity();

        helper.setImageLoad(new ImageLoadByPicasso())
                .setImageUrl(R.id.goods_pay_item_cover,item.getCoverUrl())
                .setText(R.id.goods_pay_item_price, "￥"+Utils.getPrice(item.getPrice()))
                .setText(R.id.goods_pay_item_intro, item.getTitle());
        quantityView.setQuantity(item.getNumber());
    }

    private double totalPrice;
    /** 计算总价格 */
    public String calculateTotalPrice(){
        if(DataUtil.isEmpty(data)) return "0";
        int value = 0;
        for(ShoppingCartItem item:data){
            value += item.getPrice() * item.getNumber();
        }
        totalPrice = MoneyUtil.newInstance(value).divide(100).create().doubleValue();
        //totalPrice = MoneyUtil.divide(value, 100).doubleValue();
        return MoneyUtil.replace(totalPrice);
    }
}
